home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C25 / AbstractFactory.cpp next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.9 KB  |  99 lines

  1. //: C25:AbstractFactory.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // A gaming environment
  7. #include <iostream>
  8. using namespace std;
  9.  
  10. class Obstacle {
  11. public:
  12.   virtual void action() = 0;
  13. };
  14.  
  15. class Player {
  16. public:
  17.   virtual void interactWith(Obstacle*) = 0;
  18. };
  19.  
  20. class Kitty: public Player {
  21.   virtual void interactWith(Obstacle* ob) {
  22.     cout << "Kitty has encountered a ";
  23.     ob->action();
  24.   }
  25. };
  26.  
  27. class KungFuGuy: public Player {
  28.   virtual void interactWith(Obstacle* ob) {
  29.     cout << "KungFuGuy now battles against a ";
  30.     ob->action();
  31.   }
  32. };
  33.  
  34. class Puzzle: public Obstacle {
  35. public:
  36.   void action() { cout << "Puzzle\n"; }
  37. };
  38.  
  39. class NastyWeapon: public Obstacle {
  40. public:
  41.   void action() { cout << "NastyWeapon\n"; }
  42. };
  43.  
  44. // The abstract factory:
  45. class GameElementFactory {
  46. public:
  47.   virtual Player* makePlayer() = 0;
  48.   virtual Obstacle* makeObstacle() = 0;
  49. };
  50.  
  51. // Concrete factories:
  52. class KittiesAndPuzzles : 
  53.   public GameElementFactory {
  54. public:
  55.   virtual Player* makePlayer() { 
  56.     return new Kitty;
  57.   }
  58.   virtual Obstacle* makeObstacle() {
  59.     return new Puzzle;
  60.   }
  61. };
  62.  
  63. class KillAndDismember : 
  64.   public GameElementFactory {
  65. public:
  66.   virtual Player* makePlayer() { 
  67.     return new KungFuGuy;
  68.   }
  69.   virtual Obstacle* makeObstacle() {
  70.     return new NastyWeapon;
  71.   }
  72. };
  73.  
  74. class GameEnvironment {
  75.   GameElementFactory* gef;
  76.   Player* p;
  77.   Obstacle* ob;
  78. public:
  79.   GameEnvironment(GameElementFactory* factory) :
  80.     gef(factory), p(factory->makePlayer()), 
  81.     ob(factory->makeObstacle()) {}
  82.   void play() {
  83.     p->interactWith(ob);
  84.   }
  85.   ~GameEnvironment() {
  86.     delete p;
  87.     delete ob;
  88.     delete gef;
  89.   }
  90. };
  91.  
  92. int main() {
  93.   GameEnvironment 
  94.     g1(new KittiesAndPuzzles),
  95.     g2(new KillAndDismember);
  96.   g1.play();
  97.   g2.play();
  98. } ///:~
  99.